<template>
  <view class="component" :style="{display:labelPosition==='left'?'flex':'block'}">
    <view class="component-label" v-if="label"
          :style="{ paddingBottom:labelPosition==='top'? '8px':'',marginRight:labelPosition==='left'? '16px':'',}">{{
        label
      }}
    </view>
    <picker style="width:100%" @change="bindPickerChange" :value="pickerValue" :range="list" range-key="label">
      <view class="component-value">
        <view class="component-value-text">{{
            list.find(item => {
              return item.value === value
            })?.label || placeholder
          }}
        </view>
        <view class="component-value-icon">
          <image src="/@/static/images/xiala.png"></image>
        </view>
      </view>
    </picker>

  </view>
</template>

<script setup>
import {onLoad} from "@dcloudio/uni-app";
import {watch, ref} from "vue"

const props = defineProps({
  placeholder: {
    type: String,
    default: '请选择'
  },
  label: {
    type: String,
    default: ''
  },
  labelPosition: {
    type: String,
    default: 'left' //left top
  },
  value: {
    type: String,
    default: ''
  },
  list: {
    type: Array,
    default: () => []
  }
})

const emits = defineEmits(['change', 'cancel'])

const pickerValue = ref(0)

watch(() => props.value, (val) => {
  const index = props.list.findIndex(item => {
    return item.value === val
  })
  pickerValue.value = index === -1 ? 0 : index
})

onLoad(() => {
  const index = props.list.findIndex(item => {
    return item.value === props.value
  })
  pickerValue.value = index === -1 ? 0 : index
})

const bindPickerChange = (e) => {
  emits('change', {value: props.list[e.detail.value].value, item: props.list[e.detail.value]})
}
</script>

<style lang="scss" scoped>
.component {
  align-items: center;

  &-label {
    font-size: $fontSize;
    color: $textColor;
    line-height: 22px;
    flex-shrink: 0;
  }

  &-value {
    width: calc(100% - 22px);
    background: $colorWhite;
    border: 1px solid $lineColor;
    border-radius: 2px;
    display: flex;
    height: 36px;
    padding: 0 10px;
    justify-content: space-between;

    &-text {
      display: flex;
      align-items: center;

      font-size: 14px;
      color: $textColorTitle;
      line-height: 22px;
    }

    &-icon {
      display: flex;
      align-items: center;

      image {
        width: 16px;
        height: 16px;
        vertical-align: bottom;
      }
    }
  }
}
</style>
